--[[
    框架 - 镜头
]]

local jass = require 'jass.common'
local math = math
local SetCameraField = cj.SetCameraField
local CAMERA_FIELD_ZOFFSET = cj.CAMERA_FIELD_ZOFFSET
local Vec3 = require 'xLua.module.Camera.vec3'
local Mat4 = require 'xLua.module.Camera.mat4'

mCamera = {}
setmetatable(mCamera, mCamera)

--设置玩家当前摄像头高度
function mCamera.setZ(heigh)
    SetCameraField(cj.CAMERA_FIELD_TARGET_DISTANCE, heigh, 0)
end

--- 获取玩家当前摄像头高度
function mCamera.getZ()
    return cj.GetCameraField(cj.CAMERA_FIELD_TARGET_DISTANCE)
end

--平移镜头(所有玩家)(限时)
function mCamera.setXY(x, y, time)
    cj.PanCameraToTimed(x, y, time)
end


local _curTransform = 0
local _clipSpaceSignY = 1
local _top = 20
local _bottom = 130
local _height = 600 - _top - _bottom
local _hs = _height / 600
local _matProj = Mat4.perspective(57 * (3.14159 / 180.0), 800 / _height, 1.0,
    1000.0, false, -1, _clipSpaceSignY, 0)
local _wide = false

function mCamera.SetWideScreen(v)
    _wide = v
    if v then
        _clipSpaceSignY = 1
    else
        _clipSpaceSignY = 1
    end
end

function mCamera.IsWideScreen()
    return _wide
end

function mCamera.GetView()
    local eye = Vec3.new(cj.GetCameraEyePositionX(), cj.GetCameraEyePositionZ(),
        cj.GetCameraEyePositionY())
    local target = Vec3.new(cj.GetCameraTargetPositionX(),
        0,
        cj.GetCameraTargetPositionY())
    local up = Vec3.new(0, 1, 0)
    return Mat4.lookAt(eye, target, up)
end

local function lerp(from, to, ratio)
    return from + (to - from) * ratio;
end

function mCamera.BlackBorders(top, bottom)
    _top = top * 1000
    _bottom = bottom * 1000
    _height = 600 - _top - _bottom
    _hs = _height / 600
    cj.DisplayTimedTextToPlayer(cj.Player(0), 0, 0, 60, _height)
end

function mCamera.WorldToScreen(worldPos)
    local _matViewProj
    if _wide then
        local matProj = Mat4.perspective((34) * (3.14159 / 180.0), japi.DzGetClientWidth() /
            (japi.DzGetClientHeight() * _hs), 1.0,
            1000.0, true, -1, _clipSpaceSignY, 0)
        _matViewProj = Mat4.Multiply(matProj, mCamera.GetView())
    else
        -- local matProj = Mat4.perspective((34) * (3.14159 / 180.0), 800/_height, 1.0,
        --                           1000.0, true, -1, _clipSpaceSignY, 0)
        _matViewProj = Mat4.Multiply(_matProj, mCamera.GetView())
    end
    local preTransform = Mat4.preTransforms[_curTransform]
    local out = Vec3.TransformMat4(worldPos, _matViewProj)

    local x, y = out.x, out.y
    out.x = x * preTransform[0] + y * preTransform[2] * _clipSpaceSignY
    out.y = x * preTransform[1] + y * preTransform[3] * _clipSpaceSignY

    out.x = (out.x + 1) * 0.5
    out.y = (out.y + 1) * 0.5
    out.z = out.z * 0.5 + 0.5

    return out
end

return mCamera
